package com.situ.util;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.situ.config.AliPayConfigProperities;
import com.situ.domain.entity.TOrder;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@EnableConfigurationProperties(AliPayConfigProperities.class)
@RequiredArgsConstructor
public class AliPayUtil {

    private final AliPayConfigProperities aliPayConfig;

    public String pay(TOrder order) throws AlipayApiException {

        //创建AlipayClient对象
        AlipayClient alipayClient =
                new DefaultAlipayClient(
                        aliPayConfig.getGatewayUrl(),
                        aliPayConfig.getAppId(),
                        aliPayConfig.getPrivateKey(),
                        aliPayConfig.getFormat(),
                        aliPayConfig.getCharset(),
                        aliPayConfig.getSignType(),
                        aliPayConfig.getSignType()
                );
        //创建AlipayTradePagePayRequest对象
        AlipayTradePagePayRequest aliPayRequest=new AlipayTradePagePayRequest();
        aliPayRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());
        aliPayRequest.setReturnUrl(aliPayConfig.getReturnUrl());

        String oid = order.getOid();
        Double totalPrice = order.getTotalPrice();
        Integer uid = order.getUid();
        String info = uid+""; // 支付宝在调用回调的时候会把这个信息传递回来
        String bodyInfo = oid+""; // 支付宝在调用回调的时候会把这个信息传递回来

        //支付信息设定 订单编号  支付的金额  订单名称   [商品信息   自定义数据 选择设定]   [编号 固定的写法]
        aliPayRequest.setBizContent("{\"out_trade_no\":\""+ oid +"\","
                + "\"total_amount\":\""+ totalPrice +"\","
                + "\"subject\":\""+ info +"\","
                + "\"body\":\""+ bodyInfo +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        System.out.println("请求参数"+aliPayRequest.getBizContent());
        String body = alipayClient.pageExecute(aliPayRequest).getBody();
        System.out.println("支付宝响应的信息"+body);
        return body;
    }
}
